import { nilV, toString } from "../common";
import { getErrorCode, getErrorMessage } from "./tool";
class BaseErr {
    errCode: number;
    errMsg: string;
    errType = "base";
    constructor(code: number, msg: string) {
        let targetCode = nilV(code) ? -3000 : code;
        this.errCode = targetCode;

        let targetMsg = msg || "未知错误";
        this.errMsg = targetMsg;
    }
    resMaker() {
        let code = nilV(this.errCode) ? -3000 : this.errCode;
        let targetMsg = "未知错误";
        if (this.errMsg) {
            targetMsg = this.errMsg;
        } else if (!nilV(this.errCode)) {
            targetMsg = `错误码 ${this.errCode}`;
        }
        return {
            errCode: code,
            errMsg: targetMsg,
        };
    }
}

class InsideErr extends BaseErr {
    errType = "inside";
    constructor(err: any) {
        let code = getErrorCode(err);
        let msg = getErrorMessage(err);
        msg = toString(msg);
        super(code, msg);
    }
}

class ParamErr extends BaseErr {
    errType = "param";
    constructor(key: string) {
        let msg = `${key || ""}参数错误`;
        super(-3001, msg);
    }
}

const errorHandle = {
    baseErr(code: number, msg: string) {
        return new BaseErr(code, msg);
    },
    insideErr(err: any) {
        return new InsideErr(err);
    },
    paramEr(k: string) {
        return new ParamErr(k);
    },
};

export { errorHandle, BaseErr, InsideErr, ParamErr, getErrorCode, getErrorMessage };
